<template>
  <div class="ThinkTankDocuments">
    <div class="search d-between">
      <div class="d-start">
        <div class="d-center" style="margin-right:10px;">
          <el-button
            size="medium"
            type="info"
            @click="search()"
            icon="el-icon-refresh"
            style="width:36px;height:36px;padding:0;"
          ></el-button>
          <el-button size="medium" type="primary" @click="add()">新增</el-button>
        </div>
        <div class="d-center" style="margin-right:10px;">
          <el-button size="medium" :type="selectData.length>0?'danger':'info'" @click="del()">删除</el-button>
        </div>
      </div>
      <div class="d-end">
        <div class="input d-center">
          <el-input size="medium" v-model.trim="searchs.title" placeholder="请输入内容">
            <template slot="prepend">标题：</template>
          </el-input>
          <!-- <span>标题：</span> -->
          <!-- <el-input size="medium" v-model.trim="searchs.title" placeholder="请输入标题"></el-input> -->
        </div>

        <div class="input d-start">
          <span class="select-gray d-center">分类：</span>
          <el-select
            v-model.trim="mineStatusValue"
            ref="sel"
            filterable
            placeholder="请选择"
            size="medium"
            style="width:300px"
            @visible-change="visibleDrow1"
          >
            <el-option :value="mineStatusValue" class="trees" style="width:300px">
              <!-- <el-tree
                :data="data"
                default-expand-all
                highlight-current
                :props="defaultProps"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
              ></el-tree>-->
              <div class="tree" style="overflow-y:scroll;" ref="tree">
                <tree :data="data" :level="1" @nodeClick="handleNodeClick" />
              </div>
            </el-option>
          </el-select>
          <!-- <el-select
          size="medium"
          v-model.trim="searchs.category_id"
          placeholder="请选择分类"
          style="width:100%"
        >
          <el-option
            v-for="item in this.categorylist"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
          </el-select>-->
        </div>
        <div class="d-center" style="margin-left:10px;">
          <el-button size="medium" type="info" plain @click="search()">搜索</el-button>
          <!-- icon="el-icon-search"
          style="width:36px;height:36px;padding:0;"-->
          <el-button size="medium" type="info" @click="cancel()" plain>重置</el-button>
        </div>
      </div>
    </div>
    <div class="main">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;"
        height="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-link type="primary" @click="view(scope.row)">{{scope.row.title}}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="分类名称" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="create_time" label="添加时间" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="update_time" label="更新时间" show-overflow-tooltip align="center"></el-table-column>

        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template slot-scope="scope">
            <!-- <el-button size="medium" type="success" plain @click="view(scope.row)">查看</el-button> -->
            <el-button size="medium" type="primary" plain @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="searchs.page"
          :page-size="paginate.limit"
          layout="prev, pager, next"
          :total="paginate.total"
          style="margin-top:10px;"
          class="d-center"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="文章详情"
      :visible.sync="dialogFormVisible"
      @close="close"
      width="80%"
      top="10"
      :destroy-on-close="true"
    >
      <el-form :model="form">
        <el-form-item
          prop="category_id"
          label="智库分类"
          :label-width="'100px'"
          :rules="[{ required: true, message: '该值不能为空',trigger: 'blur' }]"
        >
          <!-- 树结构 -->
          <el-select
            v-model.trim="mineStatusValue2"
            ref="sel"
            placeholder="请选择分类"
            style="width:300px"
            @visible-change="visibleDrow2"
          >
            <el-option :value="mineStatusValue2" class="trees" style="max-width:300px">
              <!-- <el-tree
                :data="data"
                default-expand-all
                highlight-current
                :props="defaultProps"
                :expand-on-click-node="false"
                @node-click="handleNodeClick2"
              ></el-tree>-->
              <div class="tree" style="overflow-y:scroll;" ref="tree2">
                <tree :data="data" :level="1" @nodeClick="handleNodeClick2" />
              </div>
            </el-option>
          </el-select>
          <!-- 树结构 -->
        </el-form-item>

        <el-form-item
          prop="title"
          label="智库名称"
          :label-width="'100px'"
          :rules="[{ required: true, message: '该值不能为空',trigger: 'blur' }]"
        >
          <el-input placeholder="请输入智库名称" size="medium" v-model.trim="form.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          prop="content"
          label="智库内容"
          :label-width="'100px'"
          :rules="[{ required: true, message: '该值不能为空',trigger: 'blur' }]"
        >
          <el-upload
            :on-success="handleSuccess"
            :show-upload-list="false"
            :format="['jpg','jpeg','png','gif']"
            :max-size="2048"
            multiple
            action="/api/index/uploads2"
            accept=".jpg, .png, .jpeg"
            >
            <Button icon="ios-cloud-upload-outline" ></Button>
          </el-upload>
          <quillEditor v-model.trim="form.content" :options="opation" ref="QuillEditor"></quillEditor>
        </el-form-item>
        <el-form-item prop="name" label="上传附件" :label-width="'100px'">
          <!-- 上传 -->
          <uploader
            :fileslists="fileslist"
            :options="options"
            :file-status-text="statusText"
            :fileurl="this.$updata"
            class="uploader-example"
            ref="uploader"
            @file-success="fileSuccess"
            @file-remove="remove"
          ></uploader>
          <!-- 上传 -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible=false">取 消</el-button>
        <el-button
          size="medium"
          type="primary"
          :disabled="buttonShow?true:false"
          @click="actions()"
        >保 存</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="查看文章" :visible.sync="dialogFormVisible2" @close="close" width="80%" top="10">
      <el-form>
        <h2 class="h2">
          <span v-text="content.title"></span> &nbsp;
          <small v-text="content.create_time"></small>
        </h2>
        <hr class="hr" />
        <div v-html="content.content" class="img"></div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible2=false">关 闭</el-button>
      </div>
    </el-dialog>-->
    <el-dialog
      title="查看文章"
      :visible.sync="dialogFormVisible2"
      width="80%"
      top="10"
      :destroy-on-close="true"
    >
      <el-form>
        <h2 class="h23">
          <span v-text="content.title"></span> &nbsp;
          <small v-text="content.create_time"></small>
        </h2>
        <hr class="hr" />
        <div v-html="content.content" class="img colora"></div>
        <uploader
          :fileslists="fileslist"
          :options="options"
          :file-status-text="statusText"
          :fileurl="this.$updata"
          class="uploader-example"
          ref="uploader"
          :app="false"
          style="margin-top:10px"
        ></uploader>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible2=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tree from "./treeSelect";
import { quillEditor } from "vue-quill-editor";
// import quillConfig from "../../../config/quill-config";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

// import mixinsFile from "@/mixins/uploadFile.js";
export default {
  // mixins: [mixinsFile],
  name: "ThinkTankDocuments",
  components: {
    quillEditor,
    tree
  },
  data() {
    return {
      //树机构初始化数据
      data: [],
      mineStatus: {},
      mineStatusValue: "",
      defaultProps: {
        children: "children",
        label: "name"
      },
      //树机构初始化数据
      mineStatus2: {},
      mineStatusValue2: "",
      name: "",
      active: "",
      dialogFormVisible: false,
      dialogFormVisible2: false,
      popShow: "",
      selectData: [],
      tableData: [],
      categorylist: [],
      form: {},
      searchs: {
        category_id: 0,
        title: "",
        page: 1,
        limit: 10
      },
      loading: true,
      buttonShow: false,
      paginate: {},
      content: {},

      //上传组件
      fileslist: [],
      options: {
        target: this.$updata + "/api/index/uploads", // '//jsonplaceholder.typicode.com/posts/',
        testChunks: false
      },
      statusText: {
        success: "成功了",
        error: "出错了",
        uploading: "上传中",
        paused: "暂停中",
        waiting: "等待中"
      },
      //上传
      opation: {
        // placeholder: "请填写描述，字数不超过2000",
        modules: {
          toolbar:{
            handlers: {
              'image': function (value) {
                  if (value) {
                      document.querySelector('.el-upload').click()
                      // alert('自定义图片')
                  } else {
                      this.quill.format('image', false);
                  }
              }
            },
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              // [{ script: "sub" }, { script: "super" }],
              // [{ indent: "-1" }, { indent: "+1" }],
              // [{ direction: "rtl" }],
              // [{ size: ["small", false, "large", "huge"] }],
              // [{ header: [1, 2, 3, 4, 5, 6, false] }],
              // [{ color: [] }, { background: [] }],
              // [{ font: [] }],
              // [{ align: [] }],
              // [{ clean: "源码编辑" }],
              ["link", "image"],
              ["sourceEditor"], //新添加的工具
            ],  // 工具栏
          }
        },
      }
    };
  },
  mounted: function() {
    console.log(this.uploadurl);

    this.getdata();
    this.$nextTick(() => {
      // window.uploader = this.$refs.uploader.uploader;
    });
  },
  methods: {
     handleSuccess (res) {
        // 获取富文本组件实例
        let quill = this.$refs.QuillEditor.quill
        // 如果上传成功
        if (res) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.code)
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
            this.$message({
              message: '图片插入失败',
              type: "error",
            });
            // 提示信息，需引入Message
            // Message.error('图片插入失败')
        }
    },
    visibleDrow1(val) {
      if (val) {
        if (this.mineStatus.id) {
          let tree = document.querySelector(`.tree${this.mineStatus.id}`);
          this.$nextTick(() => {
            this.$refs.tree.scrollTop = tree.offsetTop;
          });
          //  console.log(tree)
        }
      }
    },
    visibleDrow2(val) {
      if (val) {
        // console.log(`.tree${this.mineStatus.id}`);
        if (this.mineStatus2.id) {
          let tree = document.querySelectorAll(`.tree${this.mineStatus2.id}`)[1];
          this.$nextTick(() => {
            this.$refs.tree2.scrollTop = tree.offsetTop;
          });
          //  console.log(tree)
        }
      }
    },
    //树结构点击事件
    handleNodeClick(val) {
      this.mineStatusValue = val.name;
      this.mineStatus = val;
      this.$refs.sel.blur();
    },
    //树结构点击事件
    handleNodeClick2(val) {
      this.mineStatusValue2 = val.name;
      this.mineStatus2 = val;
      this.$refs.sel.blur();
    },

    handleCurrentChange(val) {
      if (val != this.searchs.page) {
        this.searchs.page = val;
        this.getdata();
      }
    },
    setForm() {
      this.form = {
        category_id: "",
        title: "",
        content: "",
        id: ""
      };
      // sort: 0
      this.fileslist = [];
      this.mineStatusValue2 = "";
      this.mineStatus2 = {};
    },
    setProjectForm() {
      this.projectform = {
        project_ids: "",
        admin_id: 0
      };
    },
    initDate() {
      let that = this;
      let tree = function(data) {
        data.forEach(v => {
          that.$set(v, "isShow", true);
          that.$set(v, "isChecked", false);
          if (v.children) {
            tree(v.children);
          }
        });
      };
      tree(this.data);
    },
    getdata() {
      let that = this;
      that.loading = true;
      this.$get("/api/thinktank/index", this.searchs).then(res => {
        if (res.code == 200) {
          that.paginate = { total: res.data.total, limit: res.data.limit };
          that.tableData = res.data.list;
          that.categorylist = res.data.category;
          that.data = res.data.categorytree;
          that.categorylist.unshift({ id: 0, name: "请选择分类" });
          this.initDate();
          that.search.page++;
        }

        setTimeout(function() {
          that.loading = false;
        }, 300);
      });
    },
    close() {
      //   this.dialogFormVisible = false;
    },

    handleSelectionChange(value) {
      this.selectData = value;
    },
    edit(item) {
      this.dialogFormVisible = true;
      //select树结构设置
      this.categorylist.forEach(v => {
        if (v.id == item["category_id"]) {
          this.mineStatusValue2 = v.name;
          this.mineStatus2 = v;
        }
      });
      //select树结构设置

      this.form = {
        category_id: item.category_id,
        title: item.title,
        content: item.content,
        id: item.id
      };
      //编辑设置附件列表
      this.fileslist = item.files ? item.filesarr : [];
      //编辑设置附件列表
    },
    add() {
      this.setForm();
      this.dialogFormVisible = true;
    },
    del() {
      let num = this.selectData.length;
      if (num <= 0) {
        this.$message.error("没有选中要删除的条目");
        return false;
      }
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.selectData.forEach((item, index) => {
            this.$post("/api/thinktank/deletes", {
              id: item.id
            }).then(res => {
              if (index + 1 == num) {
                this.getdata();
                this.$message({
                  title: "操作提示",
                  message: res.msg,
                  type: res.state
                });
              }
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    actions() {
      let that = this;
      let button = "添加用户操作";
      this.buttonShow = true;
      if (this.form.id) {
        button = "编辑用户操作";
      }

      //树结构参数
      this.form.category_id = this.mineStatus2.id;
      //树结构参数

      //上传参数组合
      let fileUrl = this.fileslist.map(v => {
        return v.path;
      });
      this.form.files = fileUrl.join(",");
      //上传参数组合
      this.$post("/api/thinktank/actions", this.form).then(res => {
        this.$message({
          title: button,
          message: res.msg,
          type: res.state
        });
        if (res.code == 200) {
          this.getdata();
          that.dialogFormVisible = false;
        }
        setTimeout(function() {
          that.buttonShow = false;
        }, 300);
      });
    },
    search() {
      this.searchs.page = 1;
      this.searchs.category_id = this.mineStatus.id;
      this.getdata();
    },
    cancel() {
      this.searchs = {
        category_id: 0,
        title: "",
        page: 1
      };
      this.mineStatus = {};
      this.mineStatusValue = "";
      this.getdata();
    },
    view(item) {
      this.dialogFormVisible2 = true;
      this.content = item;
    },
    //上传组件移除返回
    remove(index) {
      this.fileslist.splice(index, 1);
    },
    //上传成功返回
    fileSuccess(rootFile, file, message, chunk) {
      if (JSON.parse(message).state == "success") {
        this.fileslist.push({
          path: JSON.parse(message).code,
          name: chunk.file.name
        });
        console.log(this.fileslist);
      } else {
        this.$message({
          message: chunk.file.name + JSON.parse(message).code,
          type: "error"
        });
      }
    }
  }
};
</script>
<style lang="less">
.el-dialog img{
  max-width: 100%;
}
.el-upload,.el-upload-list{
  display: none !important;
}
.colora a{
  color: #06c;
  text-decoration: underline;
}
.uploader-example {
  width: 100%;
  font-size: 12px;
}
.uploader-example .uploader-btn {
  margin-right: 4px;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
.trees {
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: none;
  }
  .el-tree-node__content > .el-tree-node__expand-icon {
    border: 0;
  }
  .el-tree-node__content {
    height: 40px;
    border-bottom: 1px solid #eef4f5;
  }
  height: auto;
  padding: 0;
}
.ql-editor {
  min-height: 200px;
  max-height: 500px;
}
</style>

<style lang="less" scoped>
.ThinkTankDocuments {
  width: 100%;
  height: calc(100%);
  background: white;
  border-radius: 5px;
  .search {
    width: 100%;
    height: 60px;
    padding: 10px 5px;
    position: relative;
    .input {
      max-width: 300px;
      margin-left: 10px;
      span {
        flex-shrink: 0;
      }
    }
  }
  .main {
    //   width: 100%;
    height: calc(100% - 110px);
    // overflow-y: scroll;
    // position: absolute
    border: 1px solid #ebeef5;
  }
}
.img {
  font-size: 14px;
  line-height: 2;
  text-indent: 2em;
}
.h23 {
  text-align: center;
  small {
    font-weight: 400;
    font-size: 12px;
  }
}
.hr {
  margin: 10px 0;
  border: 0;
  border-top: 1px #ddd solid;
}
.img img {
  max-width: 100%;
}
.tree {
  width: 100%;
  height: 250px;
  overflow-y: scroll;
}
</style>